/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.controller;

import com.google.gson.Gson;
import com.vng.zing.survey.memcached.SurveyCache;
import com.vng.zing.survey.thrift.client.SurveyClient;
import com.vng.zing.survey.thrift.model.AnswerItem;
import com.vng.zing.survey.thrift.model.QuesType;
import com.vng.zing.survey.thrift.model.Question;
import com.vng.zing.survey.thrift.model.Response;
import com.vng.zing.survey.thrift.model.SurveyItem;
import com.vng.zing.survey.thrift.model.SurveyItemResult;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.vng.zing.survey.model.AnswerDetail;
import static com.vng.zing.survey.model.CommonModel.OFFSET;
import com.vng.zing.survey.model.CommonModel;
import com.vng.zing.survey.model.ResponeDetail;
import com.vng.zing.survey.thrift.model.ShortReponse;
import com.vng.zing.survey.thrift.model.UserType;
import com.vng.zing.survey.utility.Utility;
import java.util.Map;
import org.apache.log4j.Logger;

/**
 *
 * @author namhh
 */
public class AjaxResponseDetail extends BaseController {

    private static UserType userType = UserType.ADMIN;

    private String getResponseDetailBy(SurveyItem surveyItem, Response response) {
        String result = "";
        ResponeDetail detail = new ResponeDetail();
        detail.setTitle(surveyItem.getTitle());
        List<AnswerItem> listAnswers = response.getAnswers();
        List<Question> listQuestion = surveyItem.getQuestions();
        List<AnswerDetail> listAnswerDetail = new ArrayList<AnswerDetail>();
        AnswerDetail answerDetail;

        for (Question question : listQuestion) {
            AnswerItem answerItem = Utility.getAnswerItemById(question.getIdQues(), listAnswers);
            List<String> choice = new ArrayList<String>();
            List<String> answer = new ArrayList<String>();

            if (question.getType() == QuesType.SINGLE_LINE || question.getType() == QuesType.SINGLE_LINE) {
                if (answerItem == null) {
                    answer.add("");
                }
                choice.add("");
            } else {
                if (answerItem == null) {
                    for (int i = 0; i < question.getChoices().size(); i++) {
                        answer.add("0");
                    }
                } else {
                    answer = Arrays.asList(answerItem.getAnswer().split(","));
                }
                choice = question.getChoices();
//                if (choice.size() > answer.size()) {
//                    do {
//                        answer.add("0");
//                    } while (choice.size() > answer.size());
//
//                } else if (choice.size() < answer.size()) {
//                    do {
//                        answer.remove(answer.size() - 1);
//                    } while (choice.size() < answer.size());
//
//                }

            }

            answerDetail = new AnswerDetail(question.getTitleQues(), question.require, question.getType(), choice, answer);

            listAnswerDetail.add(answerDetail);
        }
        Gson gson = new Gson();
        detail.setAnswers(listAnswerDetail);
        System.out.println(gson.toJson(detail));
        return gson.toJson(detail);
    }

    Question getQuestionBy(SurveyItem surveyItem, int idQuestion) {
        for (Question question : surveyItem.getQuestions()) {
            if (question.getIdQues() == idQuestion) {
                return question;
            }
        }
        return null;
    }

    @Override
    public String render(HttpServletRequest request, HttpServletResponse resp) throws IOException, Exception {
try{
        if (request.getParameter("page") == null || request.getParameter("idSurvey") == null) {
            return CommonModel.toJSON("ERROR", "Tham số không hợp lệ!");
        }
        Integer page = Integer.parseInt(request.getParameter("page"));

        Integer idSurvey = Integer.parseInt(request.getParameter("idSurvey"));


        Map map = checkMember(request, userType);
        if (map.containsValue(ErrorType.FAIL) || map.containsValue(ErrorType.ERROR_SYSTEM)) {
            return CommonModel.toJSON("ERROR", (String) map.get("msg"));
        }
        int idUser = (int) map.get("msg");

        SurveyClient surveyClient = SurveyClient.getInstance();
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date date;
        page--;
       
         List<ShortReponse> shortReponse =surveyClient.getListShortResponse(idSurvey, page, OFFSET);
        TemplateDataDictionary dicResponse = TemplateDictionary.create();
        for (int i = 0; i < shortReponse.size(); i++) {
            ShortReponse response = shortReponse.get(i);
            TemplateDataDictionary sliceResponse = dicResponse.addSection("SLICE_RESPONSES");
            sliceResponse.setVariable("NUMBER", String.format("%s", page * OFFSET + i + 1));
            sliceResponse.setVariable("USER", String.format("%s", response.getDisplayName()));
            sliceResponse.setVariable("IDUSER", String.format("%s", response.getIdUser()));
            sliceResponse.setVariable("DATA", response.getData());
            date = new Date(((long) response.getTimeResponse()) * 1000L);
            sliceResponse.setVariable("TIMERESPONSE", df.format(date));
        }

        return CommonModel.getResponseTable(dicResponse);
    }
    catch(Exception ex){
         Logger.getLogger(this.getName()).error(ex.toString());
          return CommonModel.toJSON("ERROR", null);
    }
    
}
}
